package com.example.csetpp.interceptor;

import com.example.csetpp.controller.VisitorStatsController;
import com.example.csetpp.service.impl.ApiUsageCounterService;
import com.example.csetpp.service.impl.UniqueVisitorService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class ApiUsageInterceptor implements HandlerInterceptor {
    @Autowired
    private ApiUsageCounterService apiUsageCounterService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            String requestUri = request.getRequestURI();

            String interfaceIdentifier = requestUri;

            apiUsageCounterService.incrementApiUsage(interfaceIdentifier);
            log.info("以下API调用次数增加: {}", interfaceIdentifier);
        }
        return true;
    }
}
